/**
 * setting左侧菜单栏
 */
import { FC, useEffect, useState } from "react";
import { observer, inject } from "mobx-react";
import {
  Outlet,
  useLocation,
  matchRoutes,
  RouteMatch,
  Link,
} from "react-router-dom";
import { Layout, Menu, MenuProps } from "antd";
import { ITStore } from "../../store";
import router from "../../router";

const { Sider, Content } = Layout;

type TProp = {
  store: ITStore;
};
type MenuItem = Required<MenuProps>["items"][number];

const getItem = (
  label: React.ReactNode,
  key?: React.Key | null,
  icon?: React.ReactNode,
  children?: MenuItem[],
  type?: "group"
): MenuItem => {
  return {
    key,
    icon,
    children,
    label,
    type,
  } as MenuItem;
};
const SetLayout: FC<TProp | any> = ({ store }: TProp): JSX.Element => {
  const {
    globalStore: { sideMenu },
    languageStore: { lang },
  } = store;

  const { pathname } = useLocation();

  const [openKeys, setOpenKeys] = useState<string[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string>("");
  const [menuList, setMenuList] = useState<MenuItem[]>([]);

  useEffect(() => {
    let tempMenu: MenuItem[] = [];
    let list: string[] = [];
    sideMenu.forEach((item) => {
      const { icon, value, langkey, children } = item;
      list.push(value);
      let tempItem = getItem(lang[langkey], value, icon);
      if (children && children.length) {
        let tempChildren: MenuItem[] = [];
        children.forEach((sItem) => {
          tempChildren.push({
            label: <Link to={sItem.path}>{lang[sItem.langkey]}</Link>,
            key: sItem.value,
            icon: sItem.icon,
          });
        });
        tempItem = getItem(lang[langkey], value, icon, tempChildren);
      }
      tempMenu.push(tempItem);
    });
    setOpenKeys(list);
    setMenuList(tempMenu);
  }, [sideMenu, lang]);

  useEffect(() => {
    const routes: RouteMatch[] | null = matchRoutes(router, pathname);

    let lastRoute = "";
    if (routes && routes.length) {
      const { path = "" } = routes[routes.length - 1].route;
      lastRoute = path;
    }
    setSelectedKeys(lastRoute);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pathname]);

  return (
    <Layout>
      <Sider width={240}>
        <Menu
          mode="inline"
          selectedKeys={[selectedKeys]}
          openKeys={openKeys}
          style={{ height: "100%", borderRight: 0 }}
          items={menuList}
        />
      </Sider>
      <Layout className="layoutright">
        <Content className="maincont">
          <Outlet />
        </Content>
      </Layout>
    </Layout>
  );
};

export default inject("store")(observer(SetLayout));
